package com.example.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.port.fee.common.Result;
import com.port.fee.dto.FeeCalculateDTO;
import com.port.fee.dto.FeeRecordDTO;
import com.port.fee.entity.FeeRecord;
import com.port.fee.service.FeeRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 费用记录控制器
 */
@RestController
@RequestMapping("/fee")
@Tag(name = "费用管理", description = "费用记录相关接口")
public class FeeRecordController {

    private static final Logger LOGGER = LoggerFactory.getLogger(FeeRecordController.class);

    @Autowired
    private FeeRecordService feeRecordService;

    /**
     * 分页查询费用记录
     */
    @PostMapping("/list")
    @Operation(summary = "分页查询费用记录", description = "分页查询费用记录列表")
    public Result<Map<String, Object>> list(@RequestBody FeeRecordDTO feeRecordDTO) {
        try {
            // 转换对象
            FeeRecord feeRecord = new FeeRecord();
            BeanUtils.copyProperties(feeRecordDTO, feeRecord);

            // 默认值处理
            int pageNum = feeRecordDTO.getPageNum() == null ? 1 : feeRecordDTO.getPageNum();
            int pageSize = feeRecordDTO.getPageSize() == null ? 10 : feeRecordDTO.getPageSize();

            // 分页查询
            Page<FeeRecord> page = feeRecordService.listFeeRecords(feeRecord, pageNum, pageSize);

            // 封装返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("records", page.getRecords());
            data.put("total", page.getTotal());
            data.put("pages", page.getPages());
            data.put("current", page.getCurrent());
            data.put("size", page.getSize());

            return Result.success(data);
        } catch (Exception e) {
            LOGGER.error("查询费用记录异常: ", e);
            return Result.failed("查询费用记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取费用记录详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取费用记录详情", description = "根据费用ID获取详情")
    public Result<FeeRecord> getInfo(@PathVariable("id") Long id) {
        FeeRecord feeRecord = feeRecordService.getFeeRecordById(id);
        if (feeRecord != null) {
            return Result.success(feeRecord);
        } else {
            return Result.failed("费用记录不存在");
        }
    }

    /**
     * 计算费用
     */
    @PostMapping("/calculate")
    @Operation(summary = "计算费用", description = "根据货物信息计算费用")
    public Result<FeeRecord> calculate(@RequestBody FeeCalculateDTO calculateDTO) {
        try {
            if (calculateDTO.getCargoId() == null) {
                return Result.failed("货物ID不能为空");
            }

            // 解析结束日期
            Date endDate = null;
            if (calculateDTO.getEndDate() != null && !calculateDTO.getEndDate().isEmpty()) {
                try {
                    endDate = new SimpleDateFormat("yyyy-MM-dd").parse(calculateDTO.getEndDate());
                } catch (ParseException e) {
                    return Result.failed("日期格式错误，正确格式为：yyyy-MM-dd");
                }
            }

            // 计算费用
            FeeRecord feeRecord = feeRecordService.calculateFee(calculateDTO.getCargoId(), endDate);

            if (feeRecord != null) {
                return Result.success(feeRecord);
            } else {
                return Result.failed("计算费用失败");
            }
        } catch (Exception e) {
            LOGGER.error("计算费用异常: ", e);
            return Result.failed("计算费用失败: " + e.getMessage());
        }
    }

    /**
     * 保存费用记录
     */
    @PostMapping("/save")
    @Operation(summary = "保存费用记录", description = "保存计算的费用记录")
    public Result<Void> save(@RequestBody FeeRecord feeRecord) {
        try {
            if (feeRecord.getCargoId() == null) {
                return Result.failed("货物ID不能为空");
            }

            if (feeRecord.getCustomerId() == null) {
                return Result.failed("客户ID不能为空");
            }

            if (feeRecord.getFeeTypeId() == null) {
                return Result.failed("费用类型ID不能为空");
            }

            if (feeRecord.getAmount() == null) {
                return Result.failed("费用金额不能为空");
            }

            if (feeRecordService.addFeeRecord(feeRecord)) {
                return Result.success(null, "保存成功");
            } else {
                return Result.failed("保存失败");
            }
        } catch (Exception e) {
            LOGGER.error("保存费用记录异常: ", e);
            return Result.failed("保存费用记录失败: " + e.getMessage());
        }
    }

    /**
     * 确认支付
     */
    @PutMapping("/pay/{id}")
    @Operation(summary = "确认支付", description = "确认费用已支付")
    public Result<Void> confirmPayment(@PathVariable("id") Long id) {
        try {
            if (feeRecordService.confirmPayment(id)) {
                return Result.success(null, "确认支付成功");
            } else {
                return Result.failed("确认支付失败");
            }
        } catch (Exception e) {
            LOGGER.error("确认支付异常: ", e);
            return Result.failed("确认支付失败: " + e.getMessage());
        }
    }

    /**
     * 按费用类型统计收入
     */
    @GetMapping("/stats/by-type")
    @Operation(summary = "按费用类型统计", description = "按费用类型统计收入")
    public Result<List<Map<String, Object>>> statsByType() {
        try {
            List<Map<String, Object>> stats = feeRecordService.statisticsByFeeType();
            return Result.success(stats);
        } catch (Exception e) {
            LOGGER.error("统计费用异常: ", e);
            return Result.failed("统计费用失败: " + e.getMessage());
        }
    }

    /**
     * 按客户统计费用
     */
    @GetMapping("/stats/by-customer")
    @Operation(summary = "按客户统计", description = "按客户统计费用")
    public Result<List<Map<String, Object>>> statsByCustomer() {
        try {
            List<Map<String, Object>> stats = feeRecordService.statisticsByCustomer();
            return Result.success(stats);
        } catch (Exception e) {
            LOGGER.error("统计费用异常: ", e);
            return Result.failed("统计费用失败: " + e.getMessage());
        }
    }

    /**
     * 获取货物相关的费用总额
     */
    @GetMapping("/total/{cargoId}")
    @Operation(summary = "获取货物费用总额", description = "获取货物相关的费用总额")
    public Result<BigDecimal> getTotalFee(@PathVariable("cargoId") Long cargoId) {
        try {
            BigDecimal totalFee = feeRecordService.getTotalFeeByCargoId(cargoId);
            return Result.success(totalFee);
        } catch (Exception e) {
            LOGGER.error("获取费用总额异常: ", e);
            return Result.failed("获取费用总额失败: " + e.getMessage());
        }
    }
}